package com.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blog.entity.ArticleLike;
import com.blog.mapper.ArticleLikeMapper;
import com.blog.service.ArticleLikeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class ArticleLikeServiceImpl extends ServiceImpl<ArticleLikeMapper, ArticleLike> implements ArticleLikeService {

    @Override
    @Transactional
    public boolean likeArticle(Long articleId, Long userId) {
        // 检查是否已点赞
        boolean isLiked = isLiked(articleId, userId);
        
        if (isLiked) {
            // 已点赞，取消点赞
            LambdaQueryWrapper<ArticleLike> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ArticleLike::getArticleId, articleId);
            queryWrapper.eq(ArticleLike::getUserId, userId);
            
            this.remove(queryWrapper);
            return false;
        } else {
            // 未点赞，添加点赞
            ArticleLike articleLike = new ArticleLike();
            articleLike.setArticleId(articleId);
            articleLike.setUserId(userId);
            articleLike.setCreateTime(LocalDateTime.now());
            
            this.save(articleLike);
            return true;
        }
    }

    @Override
    public Integer getLikeCount(Long articleId) {
        return this.baseMapper.selectLikeCount(articleId);
    }

    @Override
    public boolean isLiked(Long articleId, Long userId) {
        return this.baseMapper.isLiked(articleId, userId) > 0;
    }
} 